package uform.ui.assembler;
import uform.ui.comp.Form;
import uform.ui.comp.Component;
import uform.model.core.IValueHandler;
import thx.util.TypeFactory;

class Assembler
{
	var _factory : TypeFactory<IComponentAssembler<Dynamic>>;
	public var form : Form;
	
	public function new(form : Form)
	{
		this.form = form;
		_factory = new TypeFactory();
		_factory.unbinded = function(c) return throw "unable to find an assembler for '" + c + "'";
		var self = this;
		
		var numberAssembler = function() return new FloatTypeAssembler(self);
		
		_factory
			.memoize(uform.model.value.BoolType,	function() return new BoolTypeAssembler(self))
			.memoize(uform.model.value.DateType,	function() return new DateTypeAssembler(self))
			.memoize(uform.model.value.FloatType,	numberAssembler)
			.memoize(uform.model.value.IntType,		numberAssembler)
			.memoize(uform.model.value.StringType,	function() return new StringTypeAssembler(self))
			.memoize(uform.model.core.Schema,		function() return new SchemaAssembler(self))
			.memoize(uform.model.cell.ArrayCell,	function() return new ArrayCellAssembler(self))
			.memoize(uform.model.cell.ValueCell,	function() return new ValueCellAssembler(self))
		;
	}
	
	public function assemble(type : IValueHandler<Dynamic>) : Component
	{
		var assembler = select(type);
		assembler.form = form;
		return assembler.assemble(type);
	}
	
	public function select(handler : IValueHandler<Dynamic>)
	{
		return _factory.get(Type.getClass(handler));
	}

	public function registerAssembler(type : Class<IValueHandler<Dynamic>>, assembler : IComponentAssembler<Dynamic>)
	{
		_factory.instance(type, assembler);
		assembler.root = this;
	}
}